//
//  NearRootViewController.m
//  SportSocial
//
//  Created by yull on 14/12/28.
//  Copyright (c) 2014年 yull. All rights reserved.
//

typedef NS_ENUM(NSInteger, NearType)
{
    NearTypeUser,
    NearTypePlace,
    NearTypeGroup,
};

#import "NearRootViewController.h"
#import "NearUserCell.h"
#import "NearGroupCell.h"
#import "NearPlaceCell.h"
#import "NearNet.h"
#import "NearUser.h"
#import "NearGroup.h"
#import "DownListView.h"
#import "BMapKit.h"

#import "NearUserAnnotation.h"
#import "NearGroupAnnotation.h"
#import "NearPlaceAnnotation.h"
#import "MyAnnotition.h"

#import "BMKAnnotationView+WebCache.h"
#import "LocationManager.h"

#import "RunViewController.h"
#import "PlaceInfoViewController.h"
#import "GroupInfoViewController.h"

#import "FunctionMethod.h"
#import "UIImage+resize.h"

#import "SearchResultViewController.h"
#import <UIViewController+MBProgressHUD.h>

#import "Place.h"

@interface NearRootViewController () <BMKMapViewDelegate,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *mapButton;
@property (nonatomic, strong) UIButton *listButton;

@property (nonatomic, strong) UIView *mapSuperView;
@property (nonatomic, strong) BMKMapView *nearMapView;

@property (nonatomic, strong) UITableView *nearTableView;

@property (nonatomic, strong) NSMutableArray *userArray;
@property (nonatomic, strong) NSMutableArray *placeArray;
@property (nonatomic, strong) NSMutableArray *groupArray;
@property (nonatomic, strong) NSArray *currentArray;

@property (nonatomic, strong) DownListView *downListView;
@property (nonatomic, strong) UIButton *downListButton;

@property (nonatomic, assign) NearType nearType;

@property (nonatomic, assign) BOOL haveChangeCenter;
@property (nonatomic, strong) UISearchBar *nearSearchBar;

@end

@implementation NearRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNaviItem];
    
    [self initDownListView];
    
    [self initSearchBar];
    
    [self initContentView];
    
    [self initSegmentControl];
    
    [self initRunButton];
    
    self.nearType = NearTypeUser;
    
    [self changeMapViewCenter];
    
    [self onMapButtonClicked:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLocationChange:) name:@"UserLocationDidChange" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogOut:) name:@"UserLogOut" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    self.nearMapView.delegate = self;
    self.topView.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.topView.hidden = YES;
    self.nearMapView.delegate = nil;
}

- (void)initNaviItem
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 28, 26);
    [leftButton setImage:[UIImage imageNamed:@"title_icon1.png"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"title_icon1_selection.png"] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(showLeft:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)showLeft:(id)sender
{
    [self.sideMenuViewController presentLeftMenuViewController];
}

- (void)initSegmentControl
{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 7, 140, 30)];
    self.topView.centerX = self.view.width / 2;
    [self.navigationController.navigationBar addSubview:self.topView];
    
    self.mapButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.mapButton.frame = CGRectMake(0, 0, self.topView.width/2, self.topView.height);
    [self.mapButton setTitle:@"地图" forState:UIControlStateNormal];
    [self.mapButton setTitleColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5] forState:UIControlStateNormal];
    [self.mapButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.mapButton setBackgroundImage:[[UIImage imageNamed:@"title_button1.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:10] forState:UIControlStateNormal];
    [self.mapButton setBackgroundImage:[[UIImage imageNamed:@"title_button1_selection.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:10] forState:UIControlStateSelected];
    self.mapButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [self.topView addSubview:self.mapButton];
    
    self.listButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.listButton.frame = CGRectMake(self.topView.width/2, 0, self.topView.width/2, self.topView.height);
    [self.listButton setTitle:@"列表" forState:UIControlStateNormal];
    [self.listButton setTitleColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5] forState:UIControlStateNormal];
    [self.listButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.listButton setBackgroundImage:[[UIImage imageNamed:@"title_button2.png"] stretchableImageWithLeftCapWidth:4 topCapHeight:10] forState:UIControlStateNormal];
    [self.listButton setBackgroundImage:[[UIImage imageNamed:@"title_button2_selection.png"] stretchableImageWithLeftCapWidth:4 topCapHeight:10] forState:UIControlStateSelected];
    self.listButton.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
    [self.topView addSubview:self.listButton];
    
    [self.mapButton addTarget:self action:@selector(onMapButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.listButton addTarget:self action:@selector(onListButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)onMapButtonClicked:(id)sender
{
    self.mapButton.selected = YES;
    self.listButton.selected = NO;
    [self.view bringSubviewToFront:self.mapSuperView];
}

- (void)onListButtonClicked:(id)sender
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    self.listButton.selected = YES;
    self.mapButton.selected = NO;
    [self.view bringSubviewToFront:self.nearTableView];
}

- (void)initRunButton
{
    CGRect rect = CGRectMake(0, 0, 92, 89);
    UIButton *runButton = [UIButton buttonWithType:UIButtonTypeCustom];
    runButton.frame = rect;
    runButton.centerX = self.nearMapView.width/2;
    runButton.top = self.nearMapView.height - runButton.height - 20;
    [runButton setBackgroundImage:[UIImage imageNamed:@"button_running"] forState:UIControlStateNormal];
    [runButton setBackgroundImage:[UIImage imageNamed:@"button_running_selection"] forState:UIControlStateHighlighted];
    [runButton setTitle:@"跑步计算" forState:UIControlStateNormal];
    [runButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    runButton.titleLabel.font = [UIFont  boldSystemFontOfSize:15.0f];
    [self.mapSuperView addSubview:runButton];
    
    [runButton addTarget:self action:@selector(onClickedRunButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initDownListView
{
    CGRect rect = CGRectMake(self.view.width - 80, 0, 80, 90.0f);
    self.downListView = [[DownListView alloc] initWithFrame:rect];
    self.downListView.selectIndex = 0;
    [self.downListView addTarget:self action:@selector(onChangeListView:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.downListView];
    
    self.downListButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.downListButton.backgroundColor = [UIColor clearColor];
    self.downListButton.frame = CGRectMake(0, 20, 80, 24);
    [self.downListButton setTitle:@"附近的人" forState:UIControlStateNormal];
    self.downListButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [self.downListButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.downListButton addTarget:self action:@selector(onDownButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:self.downListButton];
    UIBarButtonItem *fixItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixItem.width = -15;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:fixItem,item, nil];
}

- (void)initSearchBar
{
    self.nearSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    self.nearSearchBar.delegate = self;
    self.nearSearchBar.showsCancelButton = YES;
    self.nearSearchBar.translucent = NO;
    self.nearSearchBar.tintColor = [UIColor blackColor];
    
    //UIColor *backColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2f];
    //UIImage *image = [UIImage imageWithColor:backColor size:self.nearSearchBar.frame.size];
    //[UISearchBar changeSearchBarBackground:self.nearSearchBar withReplaceImage:image];
}

- (void)initContentView
{
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height - Tabbar_Height - Navibar_Height);
    
    self.mapSuperView = [[UIView alloc] initWithFrame:rect];
    [self.mapSuperView addSubview:self.nearSearchBar];
    [self.view addSubview:self.mapSuperView];
    
    self.nearMapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, self.nearSearchBar.bottom, self.mapSuperView.width, self.mapSuperView.height - self.nearSearchBar.bottom)];
    self.nearMapView.delegate = self;
    [self.mapSuperView addSubview:self.nearMapView];
    
    self.nearTableView = [[UITableView alloc] initWithFrame:rect];
    self.nearTableView.backgroundColor = [UIColor whiteColor];
    self.nearTableView.delegate = self;
    self.nearTableView.dataSource = self;
    [self.view addSubview:self.nearTableView];
    
    self.nearTableView.tableFooterView = [[UIView alloc] init];
}

- (void)changeMapViewCenter
{
    CLLocation *location = [LocationManager shareInstance].location;
    
    if (location && !self.haveChangeCenter) {
        CLLocationCoordinate2D coordinate = location.coordinate;
        BMKCoordinateSpan span = BMKCoordinateSpanMake(0.05f, 0.05f);
        BMKCoordinateRegion region = BMKCoordinateRegionMake(coordinate, span);
        [self.nearMapView setRegion:region];
        
        self.haveChangeCenter = YES;
    }
}

#pragma mark - 定位
- (void)onLocationChange:(NSNotification *)notification
{
    [self changeMapViewCenter];
    
    [self loadNearData];
}

- (void)loadNearData
{
    //CLLocation *location = [LocationManager shareInstance].location;
    CLLocationCoordinate2D location = self.nearMapView.centerCoordinate;
    switch (self.nearType) {
        case NearTypeUser:
            [self getNearUserWithLongitude:location.longitude latitude:location.latitude];
            break;
        case NearTypePlace:
            [self getNearPlaceWithLongitude:location.longitude latitude:location.latitude];
            break;
        case NearTypeGroup:
            [self getNearGroupWithLongitude:location.longitude latitude:location.latitude];
            break;
        default:
            break;
    }
}

#pragma mark - 下拉选择框
- (void)onDownButton:(id)sender
{
    if (self.downListView.hidden) {
        [self.view bringSubviewToFront:self.downListView];
        [self.downListView showList];
    }else {
        [self.downListView hideList];
    }
}

- (void)onChangeListView:(DownListView *)listView
{
    self.nearType = listView.selectIndex;
    
    [self.downListButton setTitle:[self.downListView.titleArray objectAtIndex:listView.selectIndex] forState:UIControlStateNormal];
    [self.downListView hideList];
}

- (void)setNearType:(NearType)nearType
{
    _nearType = nearType;
    
    CLLocation *location = [LocationManager shareInstance].location;
    if (location) {
        if (nearType == NearTypeUser) {
            if (!self.userArray) {
                [self loadNearData];
            }else {
                self.currentArray = self.userArray;
                [self.nearTableView reloadData];
                [self reloadNearUserMapView];
            }
        }else if (nearType == NearTypePlace) {
            if (!self.placeArray) {
                [self loadNearData];
            }else {
                self.currentArray = self.placeArray;
                [self.nearTableView reloadData];
                [self reloadNearPlaceMapView];
            }
        }else if (nearType == NearTypeGroup){
            if (!self.groupArray) {
                [self loadNearData];
            }else {
                self.currentArray = self.groupArray;
                [self.nearTableView reloadData];
                [self reloadNearGroupMapView];
            }
        }
    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.currentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.nearType == NearTypeUser) {
        return [NearUserCell nearCellDefaultHeight];
    }else if (self.nearType == NearTypeGroup) {
        return [NearGroupCell nearGroupCellHeight];
    }else {
        return [NearPlaceCell placeCellHeight];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.nearType == NearTypeUser) {
        static NSString *nearUserIdentifier = @"NearUser";
        NearUserCell *nearUserCell = [tableView dequeueReusableCellWithIdentifier:nearUserIdentifier];
        
        if (!nearUserCell) {
            nearUserCell = [[NearUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearUserIdentifier];
        }
        
        NearUser *nearUser = [self.currentArray objectAtIndex:indexPath.row];
        
        [nearUserCell drawCellWithNearUser:nearUser];
        
        return nearUserCell;
    }else if (self.nearType == NearTypeGroup) {
        static NSString *nearGroupIdentifier = @"NearGroup";
        NearGroupCell *nearGroupCell = [tableView dequeueReusableCellWithIdentifier:nearGroupIdentifier];
        
        if (!nearGroupCell) {
            nearGroupCell = [[NearGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearGroupIdentifier];
        }
        
        NearGroup *nearGroup = [self.currentArray objectAtIndex:indexPath.row];
        
        [nearGroupCell drawCellWithNearGroup:nearGroup];
        
        return nearGroupCell;
    }else {
        static NSString *nearPlaceIdentifier = @"NearPlace";
        NearPlaceCell *nearPlaceCell = [tableView dequeueReusableCellWithIdentifier:nearPlaceIdentifier];
        
        if (!nearPlaceCell) {
            nearPlaceCell = [[NearPlaceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearPlaceIdentifier];
        }
        
        Place *place = [self.currentArray objectAtIndex:indexPath.row];
        
        [nearPlaceCell drawCellWithPlace:place];
        
        return nearPlaceCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.nearType == NearTypePlace) {
        Place *place = [self.currentArray objectAtIndex:indexPath.row];
        
        PlaceInfoViewController *infoViewController = [[PlaceInfoViewController alloc] initWithPlace:place];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];

    }else if (self.nearType == NearTypeUser) {
        NearUser *nearUser = [self.currentArray objectAtIndex:indexPath.row];
        
        UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:nearUser.userId userName:nearUser.name];
        [self.navigationController pushViewController:infoViewController animated:YES];

    }else {
        NearGroup *group = [self.currentArray objectAtIndex:indexPath.row];
        
        GroupInfoViewController *infoViewController = [[GroupInfoViewController alloc] initWithNearGroup:group];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];
    }
}

#pragma mark - BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[NearUserAnnotation class]]) {
        
        BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
        if (!annotationView) {
            annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AnnotationView"];
            annotationView.canShowCallout = YES;
        }
        NearUserAnnotation *userAnnotation = (NearUserAnnotation *)annotation;
        
        UIImage *holderImage = [[UIImage imageNamed:@"zc_photo_bg"] reSizeImageToSize:CGSizeMake(36, 36)];
        [annotationView sd_setImageWithURL:[NSURL URLWithString:userAnnotation.nearUser.icon] placeholderImage:holderImage isCircle:YES];
        return annotationView;
    }if ([annotation isKindOfClass:[NearGroupAnnotation class]]) {
        
        BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
        if (!annotationView) {
            annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AnnotationView"];
            annotationView.canShowCallout = YES;
        }
        NearGroupAnnotation *groupAnnotation = (NearGroupAnnotation *)annotation;
        
        UIImage *holderImage = [[UIImage imageNamed:@"julebu"] reSizeImageToSize:CGSizeMake(36, 36)];
        [annotationView sd_setImageWithURL:[NSURL URLWithString:groupAnnotation.nearGroup.icon] placeholderImage:holderImage isCircle:NO];
        return annotationView;
    }if ([annotation isKindOfClass:[NearPlaceAnnotation class]]) {
        
        BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
        if (!annotationView) {
            annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AnnotationView"];
            annotationView.canShowCallout = YES;
        }
        NearPlaceAnnotation *placeAnnotation = (NearPlaceAnnotation *)annotation;
        
        UIImage *holderImage = [[UIImage imageNamed:@"changguan"] reSizeImageToSize:CGSizeMake(36, 36)];
        [annotationView sd_setImageWithURL:[NSURL URLWithString:placeAnnotation.nearPlace.icon] placeholderImage:holderImage isCircle:NO];
        return annotationView;
    }else if ([annotation isKindOfClass:[MyAnnotition class]]) {
        
        BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MyAnnotationView"];
        if (!annotationView) {
            annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyAnnotationView"];
            annotationView.enabled = NO;
            
            UILabel *label = [[UILabel alloc] initWithFrame:annotationView.bounds];
            label.backgroundColor = [UIColor clearColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont boldSystemFontOfSize:12.0f];
            label.textColor = [UIColor whiteColor];
            label.text = @"我";
            label.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
            label.centerY -=5;
            label.centerX -=2;
            label.tag = 99;
            [annotationView addSubview:label];
        }
        annotationView.image = [UIImage imageNamed:@"news_map_me"];

        return annotationView;
    }
    
    return nil;
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView deselectAnnotation:view.annotation animated:NO];
    
    if (self.nearType == NearTypePlace) {
        Place *place = [(NearPlaceAnnotation *)view.annotation nearPlace];
        
        PlaceInfoViewController *infoViewController = [[PlaceInfoViewController alloc] initWithPlace:place];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];
        
    }else if (self.nearType == NearTypeUser) {
        NearUser *nearUser = [(NearUserAnnotation *)view.annotation nearUser];
        
        UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:nearUser.userId userName:nearUser.name];
        [self.navigationController pushViewController:infoViewController animated:YES];
        
    }else {
        NearGroup *group = [(NearGroupAnnotation *)view.annotation nearGroup];
        
        GroupInfoViewController *infoViewController = [[GroupInfoViewController alloc] initWithNearGroup:group];
        infoViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoViewController animated:YES];
    }

}

- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    NSLog(@"region changed!");
    [self loadNearData];
}

#pragma mark - 网络数据
- (void)getNearUserWithLongitude:(double)longitude latitude:(double)latitude
{
    @weakify(self);
    [NearNet nearUserWithLatitude:latitude longitude:longitude precision:5 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [responseObject objectForKey:@"data"];
            
            if (!self.userArray) {
                self.userArray = [NSMutableArray array];
            }else {
                [self.userArray removeAllObjects];
            }
            
            for (NSDictionary *dict in dictArray) {
                if ([dict isKindOfClass:[NSNull class]]) {
                    continue;
                }
                NearUser *nearUser = [NearUser userWithDict:dict];
                nearUser.distance = [FunctionMethod distanceBetweenOrderByLat1:latitude lat2:nearUser.latitude lng1:longitude lng2:nearUser.longitude];
                
                [self.userArray addObject:nearUser];
            }
            
            if (self.nearType == NearTypeUser) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.currentArray = self.userArray;
                    [self.nearTableView reloadData];
                    [self reloadNearUserMapView];
                });
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)getNearPlaceWithLongitude:(double)longitude latitude:(double)latitude
{
    @weakify(self);
    [NearNet nearPlaceWithLatitude:latitude longitude:longitude precision:5 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [responseObject objectForKey:@"data"];
            
            if (!self.placeArray) {
                self.placeArray = [NSMutableArray array];
            }else {
                [self.placeArray removeAllObjects];
            }
            
            for (NSDictionary *dict in dictArray) {
                Place *nearPlace = [Place placeWithDict:dict];
                nearPlace.distance = [FunctionMethod distanceBetweenOrderByLat1:latitude lat2:nearPlace.latitude lng1:longitude lng2:nearPlace.longitude];
                [self.placeArray addObject:nearPlace];
            }
            
            if (self.nearType == NearTypePlace) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.currentArray = self.placeArray;
                    [self.nearTableView reloadData];
                    [self reloadNearPlaceMapView];
                });
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)getNearGroupWithLongitude:(double)longitude latitude:(double)latitude
{
    @weakify(self);
    [NearNet nearGroupWithLatitude:latitude longitude:longitude precision:5 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [responseObject objectForKey:@"data"];
            
            if (!self.groupArray) {
                self.groupArray = [NSMutableArray array];
            }else {
                [self.groupArray removeAllObjects];
            }
            
            for (NSDictionary *dict in dictArray) {
                NearGroup *nearGroup = [NearGroup nearGroupWithDict:dict];
                nearGroup.distance = [FunctionMethod distanceBetweenOrderByLat1:latitude lat2:nearGroup.latitude lng1:longitude lng2:nearGroup.longitude];
                [self.groupArray addObject:nearGroup];
            }
            
            if (self.nearType == NearTypeGroup) {
                self.currentArray = self.groupArray;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.nearTableView reloadData];
                    [self reloadNearGroupMapView];
                });
            }
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)reloadNearUserMapView
{
    [self.nearMapView removeAnnotations:self.nearMapView.annotations];
    
    NSMutableArray *annotations = [NSMutableArray array];
    
    for (NearUser *nearUser in self.userArray) {
        NearUserAnnotation *pointAnnotation = [[NearUserAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(nearUser.latitude, nearUser.longitude);
        pointAnnotation.nearUser = nearUser;
        pointAnnotation.title = @"";
        [annotations addObject:pointAnnotation];
    }
    
    BMKPointAnnotation *myAnnotation = [[MyAnnotition alloc] init];
    myAnnotation.coordinate = [LocationManager shareInstance].location.coordinate;
    myAnnotation.title = @"";
    [annotations addObject:myAnnotation];
    
    [self.nearMapView addAnnotations:annotations];
}

- (void)reloadNearPlaceMapView
{
    [self.nearMapView removeAnnotations:self.nearMapView.annotations];
    
    NSMutableArray *annotations = [NSMutableArray array];
    for (Place *nearPlace in self.placeArray) {
        NearPlaceAnnotation *pointAnnotation = [[NearPlaceAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(nearPlace.latitude, nearPlace.longitude);
        pointAnnotation.nearPlace = nearPlace;
        pointAnnotation.title = @"";
        [annotations addObject:pointAnnotation];
    }
    
    BMKPointAnnotation *myAnnotation = [[MyAnnotition alloc] init];
    myAnnotation.coordinate = [LocationManager shareInstance].location.coordinate;
    myAnnotation.title = @"";
    [annotations addObject:myAnnotation];
    
    [self.nearMapView addAnnotations:annotations];
}

- (void)reloadNearGroupMapView
{
    [self.nearMapView removeAnnotations:self.nearMapView.annotations];
    
    NSMutableArray *annotations = [NSMutableArray array];
    
    for (NearGroup *nearGroup in self.groupArray) {
        NearGroupAnnotation *pointAnnotation = [[NearGroupAnnotation alloc] init];
        pointAnnotation.coordinate = CLLocationCoordinate2DMake(nearGroup.latitude, nearGroup.longitude);
        pointAnnotation.nearGroup = nearGroup;
        pointAnnotation.title = @"";
        [annotations addObject:pointAnnotation];
    }
    
    BMKPointAnnotation *myAnnotation = [[MyAnnotition alloc] init];
    myAnnotation.coordinate = [LocationManager shareInstance].location.coordinate;
    myAnnotation.title = @"";
    [annotations addObject:myAnnotation];
    
    [self.nearMapView addAnnotations:annotations];
}

- (void)onClickedRunButton:(id)sender
{
    RunViewController *runViewController = [[RunViewController alloc] init];
    runViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:runViewController animated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];

    NSString *text = searchBar.text;
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (text.length > 0) {
        
        SearchResultViewController *controller = [[SearchResultViewController alloc] init];
        controller.searchText = searchBar.text;
        controller.searchType = (SearchType)self.nearType;
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
}

#pragma mark - 退出登录
- (void)onLogOut:(NSNotification *)notification
{
    [self.userArray removeAllObjects];
    
    [self.placeArray removeAllObjects];
    
    [self.groupArray removeAllObjects];
    
    [self.nearMapView removeAnnotations:self.nearMapView.annotations];
    
    [self.nearTableView reloadData];
    
    UIViewController *controller = self.navigationController.viewControllers.firstObject;
    
    [self.navigationController setViewControllers:@[controller] animated:NO];
}
@end
